package com.nutrition.health.controller;

import com.nutrition.health.model.DietRecord;
import com.nutrition.health.model.DietRecord.MealType;
import com.nutrition.health.service.DietRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/users/{userId}/diet-records")
@Api(tags = "饮食记录", description = "用户饮食记录和营养摄入分析相关操作")
@CrossOrigin(origins = "*")
public class DietRecordController {

    private final DietRecordService dietRecordService;

    @Autowired
    public DietRecordController(DietRecordService dietRecordService) {
        this.dietRecordService = dietRecordService;
    }

    @GetMapping
    @ApiOperation("获取用户的所有饮食记录")
    public ResponseEntity<Page<DietRecord>> getAllDietRecords(
            @PathVariable Long userId,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(defaultValue = "consumptionTime") String sortBy,
            @RequestParam(defaultValue = "DESC") String sortDir) {

        Sort.Direction direction = Sort.Direction.fromString(sortDir);
        Pageable pageable = PageRequest.of(page, size, Sort.by(direction, sortBy));

        Page<DietRecord> dietRecords = dietRecordService.getAllDietRecordsByUserId(userId, pageable);
        return new ResponseEntity<>(dietRecords, HttpStatus.OK);
    }

    @GetMapping("/{id}")
    @ApiOperation("根据ID获取饮食记录")
    public ResponseEntity<DietRecord> getDietRecordById(@PathVariable Long id) {
        return dietRecordService.getDietRecordById(id)
                .map(dietRecord -> new ResponseEntity<>(dietRecord, HttpStatus.OK))
                .orElse(new ResponseEntity<>(HttpStatus.NOT_FOUND));
    }

    @GetMapping("/meal-type/{mealType}")
    @ApiOperation("根据餐食类型获取饮食记录")
    public ResponseEntity<List<DietRecord>> getDietRecordsByMealType(
            @PathVariable Long userId,
            @PathVariable MealType mealType) {

        List<DietRecord> dietRecords = dietRecordService.getDietRecordsByUserIdAndMealType(userId, mealType);
        return new ResponseEntity<>(dietRecords, HttpStatus.OK);
    }

    @GetMapping("/date-range")
    @ApiOperation("根据日期范围获取饮食记录")
    public ResponseEntity<List<DietRecord>> getDietRecordsByDateRange(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        List<DietRecord> dietRecords = dietRecordService.getDietRecordsByUserIdAndDateRange(
                userId, startDate, endDate);

        return new ResponseEntity<>(dietRecords, HttpStatus.OK);
    }

    @PostMapping
    @ApiOperation("创建新的饮食记录")
    public ResponseEntity<DietRecord> createDietRecord(
            @PathVariable Long userId,
            @Valid @RequestBody DietRecord dietRecord) {

        DietRecord createdDietRecord = dietRecordService.createDietRecord(userId, dietRecord);
        return new ResponseEntity<>(createdDietRecord, HttpStatus.CREATED);
    }

    @PutMapping("/{id}")
    @ApiOperation("更新饮食记录")
    public ResponseEntity<DietRecord> updateDietRecord(
            @PathVariable Long id,
            @Valid @RequestBody DietRecord dietRecordDetails) {

        DietRecord updatedDietRecord = dietRecordService.updateDietRecord(id, dietRecordDetails);
        return new ResponseEntity<>(updatedDietRecord, HttpStatus.OK);
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除饮食记录")
    public ResponseEntity<Void> deleteDietRecord(@PathVariable Long id) {
        dietRecordService.deleteDietRecord(id);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @PostMapping("/{dietRecordId}/food-items/{foodItemId}")
    @ApiOperation("添加食品到饮食记录")
    public ResponseEntity<DietRecord> addFoodItemToDietRecord(
            @PathVariable Long dietRecordId,
            @PathVariable Long foodItemId) {

        DietRecord updatedDietRecord = dietRecordService.addFoodItemToDietRecord(dietRecordId, foodItemId);
        return new ResponseEntity<>(updatedDietRecord, HttpStatus.OK);
    }

    @DeleteMapping("/{dietRecordId}/food-items/{foodItemId}")
    @ApiOperation("从饮食记录中移除食品")
    public ResponseEntity<DietRecord> removeFoodItemFromDietRecord(
            @PathVariable Long dietRecordId,
            @PathVariable Long foodItemId) {

        DietRecord updatedDietRecord = dietRecordService.removeFoodItemFromDietRecord(dietRecordId, foodItemId);
        return new ResponseEntity<>(updatedDietRecord, HttpStatus.OK);
    }

    @GetMapping("/total-calories")
    @ApiOperation("计算用户在指定日期范围内的总卡路里摄入")
    public ResponseEntity<Map<String, Double>> calculateTotalCalories(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        double totalCalories = dietRecordService.calculateTotalCaloriesForUserInDateRange(
                userId, startDate, endDate);
        Map<String, Double> calories = new HashMap<>();
        calories.put("totalCalories", totalCalories);
        return new ResponseEntity<>(calories, HttpStatus.OK);
    }

    @GetMapping("/nutrient-intake")
    @ApiOperation("计算用户在指定日期范围内的营养素摄入")
    public ResponseEntity<Map<String, Double>> calculateNutrientIntake(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        Map<String, Double> nutrientIntake = dietRecordService.calculateNutrientIntakeForUserInDateRange(
                userId, startDate, endDate);

        return new ResponseEntity<>(nutrientIntake, HttpStatus.OK);
    }

    @GetMapping("/dietary-patterns")
    @ApiOperation("分析用户的饮食模式")
    public ResponseEntity<Map<String, Object>> analyzeDietaryPatterns(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {

        Map<String, Object> dietaryPatterns = dietRecordService.analyzeDietaryPatterns(
                userId, startDate, endDate);

        return new ResponseEntity<>(dietaryPatterns, HttpStatus.OK);
    }

    @GetMapping("/compare-intake")
    @ApiOperation("比较用户的实际营养摄入与推荐摄入")
    public ResponseEntity<Map<String, Object>> compareActualVsRecommendedIntake(
            @PathVariable Long userId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {

        Map<String, Object> comparison = dietRecordService.compareActualVsRecommendedIntake(userId, date);
        return new ResponseEntity<>(comparison, HttpStatus.OK);
    }

    @GetMapping("/meal-types")
    @ApiOperation("获取所有餐食类型")
    public ResponseEntity<MealType[]> getAllMealTypes() {
        return new ResponseEntity<>(MealType.values(), HttpStatus.OK);
    }
}